<!DOCTYPE html>
<html lang="en-US">
  <head>
    <link href="/assets/index.css" rel="stylesheet" type="text/css" />
    <script crossorigin="anonymous" src="/test-harness.js"></script>
    <script crossorigin="anonymous" src="/test-page-object.js"></script>
    <script crossorigin="anonymous" src="/__dist__/webchat-es5.js"></script>
  </head>
  <body>
    <main id="webchat"></main>
    <script>
      function createDirectLineForTest(options) {
        // This part of code is running in the JavaScript VM in Chromium.
        // This variable must be declared within scope
        const ONLINE = 2;

        const workingDirectLine = WebChat.createDirectLine(options);

        return {
          activity$: workingDirectLine.activity$,
          postActivity: workingDirectLine.postActivity.bind(workingDirectLine),

          connectionStatus$: new Observable(observer => {
            const subscription = workingDirectLine.connectionStatus$.subscribe({
              complete: () => observer.complete(),
              error: err => observer.error(err),
              next: connectionStatus => {
                connectionStatus !== ONLINE && observer.next(connectionStatus);
              }
            });

            return () => subscription.unsubscribe();
          })
        };
      }

      async function createWebChat(ponyfill) {
        let props = {
          directLine: createDirectLineForTest({ token: await testHelpers.token.fetchDirectLineToken() }),
          ponyfill,
          store: testHelpers.createStoreWithOptions({ ponyfill }),
          styleOptions: { spinnerAnimationBackgroundImage: 'url(/assets/staticspinner.png)' }
        };

        const render = () => WebChat.renderWebChat(props, document.getElementById('webchat'));

        render();

        return {
          updateProps: updater => {
            props = updater(props);
            render(props);
          }
        };
      }

      run(async function () {
        const clock = lolex.createClock();

        const { updateProps } = await createWebChat(clock);

        await pageConditions.webChatRendered();

        clock.tick(15000);

        await pageConditions.actionDispatched('DIRECT_LINE/CONNECT_STILL_PENDING');
        await pageConditions.connectivityStatusShown(/taking longer than usual/iu);
        await host.snapshot();

        updateProps(props => updateIn(props, ['styleOptions', 'slowConnectionAfter'], () => 20000));

        await pageConditions.connectivityStatusShown(/connecting/iu);
        await host.snapshot();

        clock.tick(5000);

        await pageConditions.connectivityStatusShown(/taking longer than usual/iu);
        await host.snapshot();
      });
    </script>
  </body>
</html>
